import urllib.request
import urllib.parse

url = 'http://www.baidu.com'
url2 = 'http://httpbin.org/post'
url3 = 'https://open.test.cibfintech.com/api/cloudwallet/validateAndOpenAcct'
douban = 'https://book.douban.com/'

# 发送包括KV 的post请求 https://cuiqingcai.com/5500.html
def post():
    url = 'http://www.baidu.com'
    url2 = 'http://httpbin.org/post'

    postcode = urllib.parse.urlencode({'name': '谭圈圈'})  # 封装传递参数
    ec_post_val = bytes(postcode, encoding='utf-8')  # 转为字节码
    resp = urllib.request.urlopen(url2, ec_post_val, timeout=5)

    print('服务期返回状态;', resp.status)
    print('服务期返回状态;', resp.getheaders())
    print('服务期返回状态;', resp.getheader('Server'))

    back = resp.read().decode('utf-8')
    print(back)


# 带浏览器头访问
# POST 请求必须大写, head头必须双引号,不然会带urilib
def hasHeader():
    data = {'name': 'tqq'}
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
        }
    data = bytes(urllib.parse.urlencode(data), encoding='utf-8')
    req = urllib.request.Request(url=douban, data=data, headers=head, method='POST')
    #发送请求
    resp = urllib.request.urlopen(req)
    result = resp.read().decode('utf-8')
    print(result)
    pass


# post()
hasHeader()
